var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var goodsRouter = require('./routes/goods');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//Redis
let redis = require('redis')
let client = redis.createClient()
client.on('ready', function (err) {
    console.log('Redis ready');
});

//拦截放在路由之前，只要有请求进来就先判断
app.use(function (req, res, next) {
    //接口白名单
    if (
        req.originalUrl == '/users/login' ||
        req.originalUrl == '/users/logout' ||
        req.originalUrl == '/users/checkLogin' ||
        req.path == "/goods/list"     //因为后面有参数，只取接口的pathName. 或者 req.originalUrl.indexOf('/goods/list') > -1
    ) return next()
    //验证登录状态
    let cookie = req.cookies.token
    //查询cookie
    if (!cookie) {
        res.statusCode = 401
        return res.json({
            status: '401',
            msg: '当前未登录',
            result: ''
        });
    }
    //查询redis
    client.get(`token-${cookie}`, (err, reply) => {
        if (!reply) {
            res.statusCode = 401
            return res.json({
                status: '401',
                msg: '当前未登录',
                result: ''
            });
        }else next()
    })
});

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

//MongoDB
//获取mongoose对象
let mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/mall', {useNewUrlParser: true});
//监听数据库是否连接成功
mongoose.connection.on("connected", () => {
    console.log("MongoDB连接成功！");
});

module.exports = app;
